package com.yaopaikeji.service.impl;

import com.yaopaikeji.dao.EmailGroupDao;
import com.yaopaikeji.dao.UserGroupRelationDao;
import com.yaopaikeji.model.EmailGroupInfo;
import com.yaopaikeji.model.User;
import com.yaopaikeji.model.UserGroupRelation;
import com.yaopaikeji.service.EmailGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class EmailGroupServiceImpl implements EmailGroupService {

    @Autowired
    private EmailGroupDao emailGroupDao;
    @Autowired
    private UserGroupRelationDao userGroupRelationDao;

    /**
     * 根据邮件组id查询整个邮件组的所有用户
     */
    @Override
    public List<User> listUsersByGroupId(int groupId){

        return userGroupRelationDao.findUsersByGroupId(groupId);
    }

    /**
     * 查询某个邮件组详情
     */
    @Override
    public EmailGroupInfo findByGroupId(int groupId){

        return emailGroupDao.findByPrimaryKey(groupId);
    }

    /**
     * 查询所有邮件组
     */
    @Override
    public List<EmailGroupInfo> listAllGroups(){

        return emailGroupDao.findAll();
    }
    /**
     * 增加一个邮件组
     */
    @Override
    public EmailGroupInfo addNewGroup(EmailGroupInfo emailGroupInfo){

        return emailGroupDao.addNewGroup(emailGroupInfo);
    }

    /**
     * 修改一个邮件组信息
     */
    @Override
    public EmailGroupInfo updateGroupInfo(EmailGroupInfo emailGroupInfo){

        return emailGroupDao.updateGroupInfo(emailGroupInfo);
    }

    /**
     * 添加某人进某个邮件组
     */
    @Override
    public boolean addMemberToEmailGroup(UserGroupRelation userGroupRelation){

        return userGroupRelationDao.addNewRelation(userGroupRelation);
    }

    /**
     * 批量添加人进邮件组
     */

    @Override
    public boolean addMembersToEmailGroup(List<UserGroupRelation> userGroupRelations) {

        return userGroupRelationDao.addNewRelations(userGroupRelations);
    }

    /**
     * 从邮件组中删除某人
     */
    @Override
    public boolean deleteUserFromGroup(UserGroupRelation userGroupRelation){

        return userGroupRelationDao.deleteRelation(userGroupRelation);
    }

    /**
     * 删除某个邮件组
     */
    @Override
    @Transactional
    public boolean deleteEmailGroup(int groupId){

        //删除user和此邮件组的关联关系，然后删除此邮件组
        return userGroupRelationDao.deleteGroupMembers(groupId) && emailGroupDao.deleteGroupById(groupId);
    }


}
